package user

import (
	"encoding/json"
	"fmt"
	"godo/libs"
	"godo/model"
	"io"
	"log"
	"net/http"
	"strconv"
	"time"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// 注册系统用户
func RegisterSysUserHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		libs.ErrorMsg(w, "invalid request method")
		return
	}

	var user model.SysUser

	// 获取请求体
	body, err := io.ReadAll(r.Body)
	if err != nil {
		log.Println("读取请求体错误:", err)
		libs.ErrorMsg(w, "invalid input")
		return
	}

	// 解析请求体
	if err := json.Unmarshal(body, &user); err != nil {
		log.Println("解析请求体错误:", err)
		libs.ErrorMsg(w, "invalid input")
		return
	}

	// 检查用户名和密码是否为空
	if user.Username == "" || user.Password == "" {
		libs.ErrorMsg(w, "username or password is empty")
		return
	}

	// 对密码进行加密
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		log.Println("密码加密失败:", err)
		libs.ErrorMsg(w, "failed to hash password")
		return
	}

	// 查找用户是否已存在
	var existingUser model.SysUser
	result := model.Db.Where("username = ?", user.Username).First(&existingUser)

	if result.Error != nil {
		// 用户不存在，创建新用户
		if result.Error == gorm.ErrRecordNotFound {
			newUser := model.SysUser{
				Username:     user.Username,
				PasswordHash: string(hashedPassword),
			}

			if err := model.Db.Create(&newUser).Error; err != nil {
				log.Println("创建用户失败:", err)
				libs.ErrorMsg(w, "failed to create user")
				return
			}

			// 创建用户后立即锁屏
			lockStatus := model.SysUserLockStatus{
				UserID:   newUser.ID,
				IsLocked: true,
				LockedAt: time.Now(),
			}

			// 创建锁屏状态记录
			if err := model.Db.Create(&lockStatus).Error; err != nil {
				log.Println("创建锁屏状态失败:", err)
				libs.ErrorMsg(w, "failed to create lock status")
				return
			}

			libs.SuccessMsg(w, newUser.ID, "user created and system locked")
			return
		} else {
			// 其他数据库错误
			log.Println("查询用户失败:", result.Error)
			libs.ErrorMsg(w, "database error")
			return
		}
	} else {
		// 用户已存在，更新密码
		existingUser.PasswordHash = string(hashedPassword)
		if err := model.Db.Save(&existingUser).Error; err != nil {
			log.Println("更新用户密码失败:", err)
			libs.ErrorMsg(w, "failed to update user password")
			return
		}

		// 更新密码后立即锁屏
		var lockStatus model.SysUserLockStatus
		result := model.Db.Where("user_id = ?", existingUser.ID).First(&lockStatus)

		now := time.Now()
		if result.Error != nil {
			// 锁屏状态记录不存在，创建新记录
			if result.Error == gorm.ErrRecordNotFound {
				lockStatus = model.SysUserLockStatus{
					UserID:   existingUser.ID,
					IsLocked: true,
					LockedAt: now,
				}

				if err := model.Db.Create(&lockStatus).Error; err != nil {
					log.Println("创建锁屏状态失败:", err)
					libs.ErrorMsg(w, "failed to create lock status")
					return
				}
			} else {
				// 其他数据库错误
				log.Println("查询锁屏状态失败:", result.Error)
				libs.ErrorMsg(w, "database error")
				return
			}
		} else {
			// 更新现有锁屏状态
			model.Db.Model(&lockStatus).Updates(map[string]interface{}{
				"is_locked": true,
				"locked_at": now,
			})
		}

		libs.SuccessMsg(w, existingUser.ID, "user password updated and system locked")
		return
	}
}

// 系统用户登录（锁屏）
func LockedScreenHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		libs.ErrorMsg(w, "invalid request method")
		return
	}

	var req model.SysUser
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		libs.ErrorMsg(w, "invalid input")
		return
	}

	var user model.SysUser
	result := model.Db.Where("username = ?", req.Username).First(&user)
	if result.Error != nil {
		libs.ErrorMsg(w, "invalid username or password")
		return
	}

	// 验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
		libs.ErrorMsg(w, "invalid username or password")
		return
	}

	// 登录成功，更新或创建锁屏状态为 true
	lockStatus := model.SysUserLockStatus{
		UserID:   user.ID,
		IsLocked: true,
	}

	// 使用 FirstOrCreate 来查找或创建锁屏状态记录
	result = model.Db.Where("user_id = ?", user.ID).FirstOrCreate(&lockStatus)
	if result.Error != nil {
		log.Println("创建或更新锁屏状态失败:", result.Error)
		libs.ErrorMsg(w, "failed to update lock status")
		return
	}

	// 更新锁屏状态和锁屏时间
	now := time.Now()
	model.Db.Model(&lockStatus).Updates(map[string]interface{}{
		"is_locked": true,
		"locked_at": now,
	})

	libs.SuccessMsg(w, fmt.Sprint(user.ID), "system locked")
}

// 系统用户登录（解锁）
func UnLockScreenHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		libs.ErrorMsg(w, "invalid request method")
		return
	}

	var req model.SysUser
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		libs.ErrorMsg(w, "invalid input")
		return
	}

	var user model.SysUser
	result := model.Db.Where("username = ?", req.Username).First(&user)
	if result.Error != nil {
		libs.ErrorMsg(w, "invalid username or password")
		return
	}

	// 验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
		libs.ErrorMsg(w, "invalid username or password")
		return
	}

	// 登录成功，更新锁屏状态为 false
	lockStatus := model.SysUserLockStatus{
		UserID:   user.ID,
		IsLocked: false,
	}

	// 使用 FirstOrCreate 来查找或创建锁屏状态记录
	result = model.Db.Where("user_id = ?", user.ID).FirstOrCreate(&lockStatus)
	if result.Error != nil {
		log.Println("创建或更新锁屏状态失败:", result.Error)
		libs.ErrorMsg(w, "failed to update lock status")
		return
	}

	// 更新锁屏状态和解锁时间
	now := time.Now()
	model.Db.Model(&lockStatus).Updates(map[string]interface{}{
		"is_locked":   false,
		"unlocked_at": now,
	})

	libs.SuccessMsg(w, nil, "system unlock")
}

// 检查锁屏状态
func CheckLockedScreenHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		libs.ErrorMsg(w, "invalid request method")
		return
	}

	uidStr := r.Header.Get("sysuser")
	uid, err := strconv.Atoi(uidStr)
	if err != nil {
		uid = 0
	}
	// 如果没有传用户ID，则取最新锁屏的一个用户
	if uid == 0 {
		var latestLockedUser model.SysUserLockStatus

		// 查找最新锁屏且状态为锁定的用户（按锁屏时间排序）
		result := model.Db.Where("is_locked = ?", true).Order("locked_at DESC").First(&latestLockedUser)
		if result.Error != nil {
			if result.Error == gorm.ErrRecordNotFound {
				// 没有找到锁屏用户，返回0
				libs.SuccessMsg(w, 0, "")
				return
			} else {
				log.Println("查询锁屏状态失败:", result.Error)
				libs.ErrorMsg(w, "failed to query lock status")
				return
			}
		}

		// 返回最新锁屏用户的ID
		libs.SuccessMsg(w, latestLockedUser.UserID, "")
		return
	}

	var lockStatus model.SysUserLockStatus
	result := model.Db.Where("user_id = ?", uid).First(&lockStatus)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			// 用户没有锁屏记录，默认为未锁屏，返回0
			libs.SuccessMsg(w, 0, "")
			return
		} else {
			log.Println("查询锁屏状态失败:", result.Error)
			libs.ErrorMsg(w, "failed to query lock status")
			return
		}
	}

	// 如果用户已锁屏，返回用户ID，否则返回0
	if lockStatus.IsLocked {
		libs.SuccessMsg(w, lockStatus.UserID, "")
	} else {
		libs.SuccessMsg(w, 0, "")
	}
}
